using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using PuzzleDulex.bamboo;
using System.Threading;
using System.Diagnostics;
using PuzzleDeluxe.bamboo;
using JumpyCat.bamboo;
using AnimalSound.bamboo;

namespace PuzzleDulex
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        public static GraphicsDeviceManager sharedGraphics;
        SpriteBatch spriteBatch;

        public static SpriteFont globalTextFontNormal = null;
        public static SpriteFont globalTextFontLarge = null;
        public static SpriteFont globalTextFontSmall = null;
        public static ContentManager sharedContent = null;
        private int fps;

        public static int currentGameState;

        //private bool paused;
        //private bool stoped;


        //	Main menu button
        private ButtonMenu playButton;
        private ButtonMenu helpButton;
        private ButtonMenu aboutButton;
        private ButtonMenu exitButton;

        //	Back button to main menu
        private ButtonMenu backArrowButton;

        private ButtonMenu volumeOnButton;
        private ButtonMenu volumeOffButton;

        private ButtonMenu headPhoneButton;
        private ButtonMenu finishAnswerButton;
        private ButtonMenu clearAnswerButton;


        //	In game menu
        private ButtonMenu pauseButton;

        private ButtonMenu resumeButton;
        private ButtonMenu pauseGoToMenuButton;


        //	Game Over menu
        private ButtonMenu gotoMainButton;
        private ButtonMenu retryButton;

        //	Confirm Delete menu
        private ButtonMenu yesExitButton;
        private ButtonMenu noExitButton;

        private Texture2D backgroundImage;
        private Texture2D inGameBgImage;
        private Texture2D logoImage;
        private Texture2D catLogoImage;
        private Texture2D bambooGroupImage;
        private Texture2D bambooLogo;
        private Texture2D introTextImage;
        private Texture2D boardInGameImage;

        private SimpleSoundManager soundManager;

        private AnimalImageSoundManager gameSoundImageManager;


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth = 480;
            graphics.PreferredBackBufferHeight = 800;
            graphics.IsFullScreen = true;

            Game1.sharedGraphics = graphics;
            Content.RootDirectory = "Content";
            Game1.sharedContent = Content;

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

            // Extend battery life under lock.
            InactiveSleepTime = TimeSpan.FromSeconds(1);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            this.fps = 30;
            currentGameState = GAME_STATE.SPLASH_SCREEN_STATE;

            try
            {

                globalTextFontSmall = Content.Load<SpriteFont>("fontSmall");
                globalTextFontNormal = Content.Load<SpriteFont>("fontMedium");
                globalTextFontLarge = Content.Load<SpriteFont>("fontLarge");


                backgroundImage = Content.Load<Texture2D>(PathResource.BACKGROUND_IMAGE);
                inGameBgImage = Content.Load<Texture2D>(PathResource.IN_GAME_BG_IMAGE);
                bambooGroupImage = Content.Load<Texture2D>("bambooGroup");
                bambooLogo = Content.Load<Texture2D>("bambooLogo");
                introTextImage = Content.Load<Texture2D>("introText");

                logoImage = Content.Load<Texture2D>(PathResource.LOGO_IMAGE);
                catLogoImage = Content.Load<Texture2D>(PathResource.CAT_LOGO_IMAGE);
                
                playButton = new ButtonMenu(0, PathResource.BTN_PLAY_IMAGE);
                helpButton = new ButtonMenu(1, PathResource.BTN_HELP_IMAGE);
                aboutButton = new ButtonMenu(2, PathResource.BTN_ABOUT_IMAGE);
                exitButton = new ButtonMenu(3, PathResource.BTN_EXIT_IMAGE);

                pauseButton = new ButtonMenu(PathResource.BTN_PAUSE_GAME_IMAGE);
                resumeButton = new ButtonMenu(PathResource.BTN_RESUME_IMAGE, 270);
                pauseGoToMenuButton = new ButtonMenu(PathResource.BTN_MAINMENU_IMAGE, 350);

                volumeOnButton = new ButtonMenu(PathResource.VOLUME_IMAGE, 340, 10, 55, 55);
                volumeOffButton = new ButtonMenu(PathResource.VOLUME_MUTE_IMAGE, 340, 10, 55, 55);

                headPhoneButton = new ButtonMenu(PathResource.BTN_HEADPHONE_IMAGE, 30, 10, 55, 55);
                finishAnswerButton = new ButtonMenu(PathResource.BTN_FINISH_IMAGE, 140, 10, 55, 55);
                clearAnswerButton = new ButtonMenu(PathResource.BTN_CLEAR_IMAGE, 215, 10, 55, 55);


                retryButton = new ButtonMenu(PathResource.BTN_RETRY_GAME_IMAGE, 450);
                gotoMainButton = new ButtonMenu(PathResource.BTN_MAINMENU_IMAGE, 530);
                backArrowButton = new ButtonMenu(PathResource.BTN_BACK_IMAGE, 10, 20);

                yesExitButton = new ButtonMenu(PathResource.BTN_YES_EXIT_IMAGE, 130, 280);
                noExitButton = new ButtonMenu(PathResource.BTN_NO_EXIT_IMAGE, 130, 360);
                boardInGameImage = Content.Load<Texture2D>(PathResource.BOARD_IN_GAME_IMAGE);

                soundManager = new SimpleSoundManager(Content);

                gameSoundImageManager = new AnimalImageSoundManager(GameEngine.NUM_SOUND_LEVEL_3, Content);

            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                System.Diagnostics.Debug.WriteLine(e.Message.ToString());
            }

            TimerCallback callback = new TimerCallback(ChangeToMenuState);

            // create a one second timer tick
            Timer stateTimer = new Timer(callback, null, 3500, 0);

        }


        static public void ChangeToMenuState(Object stateInfo)
        {
            Debug.WriteLine("ChangeToMenuState");
            Game1.currentGameState = GAME_STATE.MENU_STATE;
        }


        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// 

        public void handleEventTouch(int xPoint, int yPoint)
        {

            switch (Game1.currentGameState)
            {
                case GAME_STATE.MENU_STATE:
                    {

                        if (volumeOnButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.isMuted = !SimpleSoundManager.isMuted;
                        }

                        if (playButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();

                            Game1.currentGameState = GAME_STATE.PLAY_STATE;
                            this.resetGame();

                        }

                        if (helpButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            Game1.currentGameState = GAME_STATE.HELP_STATE;

                        }
                        if (aboutButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            Game1.currentGameState = GAME_STATE.ABOUT_STATE;

                        }


                        if (exitButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            Game1.currentGameState = GAME_STATE.CONFIRM_EXIT_STATE;

                        }

                    }
                    break;

                case GAME_STATE.PLAY_STATE:
                    {

                        if (pauseButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            Game1.currentGameState = GAME_STATE.IN_GAME_PAUSE_STATE;

                        }

                        if (headPhoneButton.isTouchInsideButton(xPoint,yPoint) && gameSoundImageManager.showHeadphoneButton)
                        {
                            SimpleSoundManager.PlayClickSound();
                            gameSoundImageManager.showHeadphoneButton = false;
                            gameSoundImageManager.soundManager.stopPlayList = false;

                        }

                        if (clearAnswerButton.isTouchInsideButton(xPoint, yPoint) && clearAnswerButton.isShow)
                        {
                            SimpleSoundManager.PlayClickSound();
                            gameSoundImageManager.clearSelectedIndex();
                        }

                        if (finishAnswerButton.isTouchInsideButton(xPoint, yPoint) && finishAnswerButton.isShow)
                        {
                            SimpleSoundManager.PlayClickSound();
                            // show result
                        }


                        if (volumeOnButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.isMuted = !SimpleSoundManager.isMuted;
                           
                        }

                        gameSoundImageManager.handleTouchInTile(xPoint, yPoint);


                    }
                    break;
                case GAME_STATE.IN_GAME_PAUSE_STATE:
                    {



                        if (resumeButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            Game1.currentGameState = GAME_STATE.PLAY_STATE;

                        }

                        if (pauseGoToMenuButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            resetGame();
                            Game1.currentGameState = GAME_STATE.MENU_STATE;
                        }

                    }
                    break;

                case GAME_STATE.GAMEOVER_STATE:
                    {

                        if (retryButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            resetGame();
                            Game1.currentGameState = GAME_STATE.PLAY_STATE;

                        }

                        if (gotoMainButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            resetGame();
                            Game1.currentGameState = GAME_STATE.MENU_STATE;
                        }

                    }
                    break;

                case GAME_STATE.HELP_STATE:
                    {

                        if (backArrowButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            Game1.currentGameState = GAME_STATE.MENU_STATE;
                        }

                    }
                    break;

                case GAME_STATE.ABOUT_STATE:
                    {
                        if (backArrowButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            Game1.currentGameState = GAME_STATE.MENU_STATE;
                        }

                    }
                    break;
                case GAME_STATE.CONFIRM_EXIT_STATE:
                    {

                        if (noExitButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            SimpleSoundManager.PlayClickSound();
                            Game1.currentGameState = GAME_STATE.MENU_STATE;
                        }

                        if (yesExitButton.isTouchInsideButton(xPoint, yPoint))
                        {
                            this.Exit();
                        }

                    }
                    break;

                default:
                    break;
            }

        }

        private void resetGame()
        {
            gameSoundImageManager.Random(GameEngine.NUM_SOUND_LEVEL_3);

        }

        public void update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                Debug.WriteLine("Press back button");

                SimpleSoundManager.PlayClickSound();

                switch (Game1.currentGameState)
                {

                    case GAME_STATE.MENU_STATE:
                        {
                            Game1.currentGameState = GAME_STATE.CONFIRM_EXIT_STATE;
                        }
                        break;

                    case GAME_STATE.PLAY_STATE:
                        {

                            Game1.currentGameState = GAME_STATE.IN_GAME_PAUSE_STATE;

                        }
                        break;
                    case GAME_STATE.IN_GAME_PAUSE_STATE:
                        {
                            Game1.currentGameState = GAME_STATE.PLAY_STATE;
                        }
                        break;
                    case GAME_STATE.GAMEOVER_STATE:
                        {
                            Game1.currentGameState = GAME_STATE.MENU_STATE;
                        }
                        break;

                    case GAME_STATE.HELP_STATE:
                        {
                            Game1.currentGameState = GAME_STATE.MENU_STATE;
                        }
                        break;

                    case GAME_STATE.ABOUT_STATE:
                        {
                            Game1.currentGameState = GAME_STATE.MENU_STATE;
                        }
                        break;

                    case GAME_STATE.CONFIRM_EXIT_STATE:
                        {
                            Game1.currentGameState = GAME_STATE.MENU_STATE;
                        }
                        break;

                    case GAME_STATE.SPLASH_SCREEN_STATE:
                        {
                            this.Exit();
                        }
                        break;

                    default:
                        break;
                }

            }



            switch (Game1.currentGameState)
            {

                case GAME_STATE.MENU_STATE:
                    {

                    }
                    break;
                case GAME_STATE.PLAY_STATE:
                    {
                        if (!gameSoundImageManager.soundManager.stopPlayList)
                        {
                            gameSoundImageManager.PlayAnimalsSounds();
                        }
                       
                    }
                    break;
                case GAME_STATE.IN_GAME_PAUSE_STATE:
                    {

                    }
                    break;
                case GAME_STATE.GAMEOVER_STATE:
                    {

                    }
                    break;

                case GAME_STATE.HELP_STATE:
                    {

                    }
                    break;

                case GAME_STATE.ABOUT_STATE:
                    {

                    }
                    break;

                case GAME_STATE.CONFIRM_EXIT_STATE:
                    {

                    }
                    break;

                default:
                    break;
            }

        }



        protected override void Update(GameTime gameTime)
        {

            // Process touch events
            TouchCollection touchCollection = TouchPanel.GetState();
            if (touchCollection.Count > 0)
            {
                TouchLocation firstTouch = touchCollection[0];
                if (firstTouch.State == TouchLocationState.Pressed)
                {
                    handleEventTouch((int)firstTouch.Position.X, (int)firstTouch.Position.Y);
                }
            }

            update(gameTime);

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// 

        public void paint(SpriteBatch g)
        {

            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            switch (Game1.currentGameState)
            {
                case GAME_STATE.MENU_STATE:
                    {
                        

                        g.Draw(backgroundImage, new Rectangle(0, 0, GameEngine.SCREEN_WIDTH, GameEngine.SCREEN_HEIGHT), Color.White);
                        g.Draw(catLogoImage, new Rectangle(20, 70, 160, 160), Color.White);
                        g.Draw(logoImage, new Rectangle(80 * 2 + 30, 85, 280, 65), Color.White);

                        if (SimpleSoundManager.isMuted)
                        {
                            volumeOffButton.renderByRect(g);
                        }
                        else
                        {
                            volumeOnButton.renderByRect(g);
                        }

                        playButton.render(g);
                        helpButton.render(g);
                        aboutButton.render(g);
                        exitButton.render(g);
                    }
                    break;

                case GAME_STATE.PLAY_STATE:
                    {

                        g.Draw(inGameBgImage, new Rectangle(0, 0, GameEngine.SCREEN_WIDTH, GameEngine.SCREEN_HEIGHT), Color.White);
                        pauseButton.render(g);

                        gameSoundImageManager.DrawAnimalImage(g);

                        if (gameSoundImageManager.showHeadphoneButton)
                        {
                            headPhoneButton.renderByRect(g);
                        }

                        if (gameSoundImageManager.currentOrderIndex >= gameSoundImageManager.imageManager.listAnimalImage.Count - 1)
                        {
                            finishAnswerButton.renderByRect(g);
                            finishAnswerButton.isShow = true;
                        }
                        else
                        {
                            finishAnswerButton.isShow = false;
                        }

                        if (gameSoundImageManager.currentOrderIndex >= 0)
                        {
                            clearAnswerButton.renderByRect(g);
                            clearAnswerButton.isShow = true;
                        }
                        else
                        {
                            clearAnswerButton.isShow = false;
                        }

                        if (SimpleSoundManager.isMuted)
                        {
                            volumeOffButton.renderByRect(g);
                        }
                        else
                        {
                            volumeOnButton.renderByRect(g);
                        }


                    }
                    break;
                case GAME_STATE.IN_GAME_PAUSE_STATE:
                    {
                        g.Draw(inGameBgImage, new Rectangle(0, 0, GameEngine.SCREEN_WIDTH, GameEngine.SCREEN_HEIGHT), Color.White);

                        gameSoundImageManager.DrawAnimalImage(g);

                        if (gameSoundImageManager.showHeadphoneButton)
                        {
                            headPhoneButton.renderByRect(g);
                        }

                        if (gameSoundImageManager.currentOrderIndex >= gameSoundImageManager.imageManager.listAnimalImage.Count - 1)
                        {
                            finishAnswerButton.renderByRect(g);
                        }

                        if (gameSoundImageManager.currentOrderIndex >= 0)
                        {
                            clearAnswerButton.renderByRect(g);
                        }

                        gameSoundImageManager.DrawAnimalImage(g);
                        

                        if (SimpleSoundManager.isMuted)
                        {
                            volumeOffButton.renderByRect(g);
                        }
                        else
                        {
                            volumeOnButton.renderByRect(g);
                        }

                        
                        resumeButton.render(g);
                        pauseGoToMenuButton.render(g);

                    }
                    break;
                case GAME_STATE.GAMEOVER_STATE:
                    {

                        g.Draw(inGameBgImage, new Rectangle(0, 0, GameEngine.SCREEN_WIDTH, GameEngine.SCREEN_HEIGHT), Color.White);
                        g.Draw(boardInGameImage, new Rectangle(40, 150, 400, 500), Color.White);

                        TextUtil.printString(g, 160, 170, "Finish", Font.SIZE_LARGE, Color.Red);
                       
                        retryButton.render(g);
                        gotoMainButton.render(g);
                    }
                    break;

                case GAME_STATE.HELP_STATE:
                    {
                        g.Draw(inGameBgImage, new Rectangle(0, 0, GameEngine.SCREEN_WIDTH, GameEngine.SCREEN_HEIGHT), Color.White);
                        backArrowButton.render(g);
                        String helpString = "Your mission is very simple.";
                        String helpString1 = "You will hear a list of animal sounds";
                        String helpString2 = "You will see some animal photo in game";
                        String helpString3 = "After hearing, touch inside animal photo";
                        String helpString4 = "to order animal photos followed ";
                        String helpString5 = "the order of animal sounds you have heard";
                        String helpString6 = "Play and enjoy it :D";

                        TextUtil.printString(g, 160, 50, "HELP", Font.SIZE_LARGE,
                                Color.Red);
                        TextUtil.printString(g, 20, 120, helpString, Font.SIZE_SMALL,
                                Color.Black);
                        TextUtil.printString(g, 20, 160, helpString1, Font.SIZE_SMALL,
                                Color.Black);
                        TextUtil.printString(g, 20, 200, helpString2, Font.SIZE_SMALL,
                                Color.Black);
                        TextUtil.printString(g, 20, 240, helpString3, Font.SIZE_SMALL,
                                Color.Black);
                        TextUtil.printString(g, 20, 280, helpString4, Font.SIZE_SMALL,
                                Color.Black);
                        TextUtil.printString(g, 20, 320, helpString5, Font.SIZE_SMALL,
                                Color.Black);
                        TextUtil.printString(g, 20, 360, helpString6, Font.SIZE_SMALL,
                                Color.Black);
                        TextUtil.printString(g, 80, 430, "TRY YOUR BEST", Font.SIZE_LARGE,
                                Color.Red);

                    }
                    break;

                case GAME_STATE.ABOUT_STATE:
                    {
                        g.Draw(inGameBgImage, new Rectangle(0, 0, GameEngine.SCREEN_WIDTH, GameEngine.SCREEN_HEIGHT), Color.White);
                        backArrowButton.render(g);
                        TextUtil.printString(g, 170, 100, "About", Font.SIZE_LARGE,
                                Color.BurlyWood);
                        TextUtil.printString(g, 150, 150, "Animal Sound", Font.SIZE_MEDIUM,
                                Color.Red);
                        TextUtil.printString(g, 140, 200, "Version 1.0", Font.SIZE_MEDIUM,
                                Color.SpringGreen);
                        TextUtil.printString(g, 40, 260, "Developed By", Font.SIZE_SMALL,
                                Color.Sienna);
                        TextUtil.printString(g, 210, 250, "Bamboo Group", Font.SIZE_MEDIUM,
                                Color.Blue);

                        g.Draw(bambooGroupImage, new Rectangle(40, 350, 400, 320), Color.White);
                    }
                    break;

                case GAME_STATE.CONFIRM_EXIT_STATE:
                    {
                        g.Draw(backgroundImage, new Rectangle(0, 0, GameEngine.SCREEN_WIDTH, GameEngine.SCREEN_HEIGHT), Color.White);
                        TextUtil.printString(g, 100, 200, "ARE YOU SURE?", Font.SIZE_LARGE, Color.Red);
                        yesExitButton.render(g);
                        noExitButton.render(g);
                    }
                    break;

                case GAME_STATE.SPLASH_SCREEN_STATE:
                    {
                        g.Draw(bambooGroupImage, new Rectangle(0, 0, GameEngine.SCREEN_WIDTH, GameEngine.SCREEN_HEIGHT), Color.White);
                        g.Draw(bambooLogo, new Rectangle(30, 150, bambooLogo.Width, bambooLogo.Height), Color.White);
                        g.Draw(introTextImage, new Rectangle(60, 240, introTextImage.Width, introTextImage.Height), Color.White);
                    }
                    break;

                default:
                    break;
            }

            spriteBatch.End();

        }


        protected override void Draw(GameTime gameTime)
        {
            this.paint(spriteBatch);
            base.Draw(gameTime);
        }
    }
}
